/**
 * Notes: 宠物模块业务逻辑 - 宠物门店预约小程序
 * Date: 2025-01-27 
 */

const BaseService = require('./base_service.js');
const PetModel = require('../model/pet_model.js');
const timeUtil = require('../../framework/utils/time_util.js');

class PetService extends BaseService {

	/**
	 * 获取用户的宠物列表
	 * @param {string} userId 用户ID
	 * @returns {Array} 宠物列表
	 */
	async getPetList(userId) {
		let where = {
			userId: userId
		};
		let fields = '_id,name,gender,category,weight,isSterilized,species,avatar,birthday,createTime';
		let orderBy = { createTime: -1 };
		
		return await PetModel.getAll(where, fields, orderBy, 100);
	}

	/**
	 * 获取单个宠物详情
	 * @param {string} petId 宠物ID
	 * @param {string} userId 用户ID
	 * @returns {Object} 宠物详情
	 */
	async getPetDetail(petId, userId) {
		let where = {
			_id: petId,
			userId: userId
		};
		let fields = '_id,userId,name,gender,category,weight,isSterilized,species,avatar,birthday,createTime,updateTime';
		
		return await PetModel.getOne(where, fields);
	}

	/**
	 * 添加宠物
	 * @param {string} userId 用户ID
	 * @param {Object} petData 宠物数据
	 * @returns {Object} 添加结果
	 */
	async addPet(userId, petData) {
		let {
			name,
			gender,
			category,
			weight,
			isSterilized,
			species,
			avatar,
			birthday
		} = petData;

		// 验证必填字段
		if (!name || !gender || !category) {
			throw new Error('宠物昵称、性别和类别为必填项');
		}

		// 验证性别值
		if (!Object.values(PetModel.GENDER).includes(gender)) {
			throw new Error('性别值无效');
		}

		// 验证类别值
		if (!Object.values(PetModel.CATEGORY).includes(category)) {
			throw new Error('类别值无效');
		}

		let data = {
			_id: this.generateId(),
			userId: userId,
			name: name,
			gender: gender,
			category: category,
			weight: weight || 0,
			isSterilized: isSterilized || false,
			species: species || '',
			avatar: avatar || '',
			birthday: birthday || 0,
			createTime: timeUtil.time(),
			updateTime: timeUtil.time()
		};

		await PetModel.insert(data);
		return data;
	}

	/**
	 * 更新宠物信息
	 * @param {string} petId 宠物ID
	 * @param {string} userId 用户ID
	 * @param {Object} petData 宠物数据
	 * @returns {Object} 更新结果
	 */
	async updatePet(petId, userId, petData) {
		let where = {
			_id: petId,
			userId: userId
		};

		// 检查宠物是否存在
		let pet = await PetModel.getOne(where);
		if (!pet) {
			throw new Error('宠物不存在或无权限操作');
		}

		let updateData = {
			updateTime: timeUtil.time()
		};

		// 只更新传入的字段
		if (petData.name !== undefined) updateData.name = petData.name;
		if (petData.gender !== undefined) {
			if (!Object.values(PetModel.GENDER).includes(petData.gender)) {
				throw new Error('性别值无效');
			}
			updateData.gender = petData.gender;
		}
		if (petData.category !== undefined) {
			if (!Object.values(PetModel.CATEGORY).includes(petData.category)) {
				throw new Error('类别值无效');
			}
			updateData.category = petData.category;
		}
		if (petData.weight !== undefined) updateData.weight = petData.weight;
		if (petData.isSterilized !== undefined) updateData.isSterilized = petData.isSterilized;
		if (petData.species !== undefined) updateData.species = petData.species;
		if (petData.avatar !== undefined) updateData.avatar = petData.avatar;
		if (petData.birthday !== undefined) updateData.birthday = petData.birthday;

		await PetModel.edit(where, updateData);
		return await this.getPetDetail(petId, userId);
	}

	/**
	 * 删除宠物
	 * @param {string} petId 宠物ID
	 * @param {string} userId 用户ID
	 * @returns {boolean} 删除结果
	 */
	async deletePet(petId, userId) {
		let where = {
			_id: petId,
			userId: userId
		};

		// 检查宠物是否存在
		let pet = await PetModel.getOne(where);
		if (!pet) {
			throw new Error('宠物不存在或无权限操作');
		}

		// TODO: 检查宠物是否有关联的预约单，如果有则不允许删除
		// 这里可以添加预约单关联检查逻辑

		await PetModel.del(where);
		return true;
	}

	/**
	 * 获取宠物统计信息
	 * @param {string} userId 用户ID
	 * @returns {Object} 统计信息
	 */
	async getPetStats(userId) {
		let where = {
			userId: userId
		};

		let totalCount = await PetModel.count(where);
		
		// 按类别统计
		let categoryStats = await PetModel.groupCount(where, 'category');
		
		// 按性别统计
		let genderStats = await PetModel.groupCount(where, 'gender');

		return {
			totalCount: totalCount,
			categoryStats: categoryStats,
			genderStats: genderStats
		};
	}

	/**
	 * 生成唯一ID
	 * @returns {string} 唯一ID
	 */
	generateId() {
		return 'pet_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
	}
}

module.exports = PetService;
